// import React, { useState } from 'react';
// // import {
// //   DesktopOutlined,
// //   FileOutlined,
// //   PieChartOutlined,
// //   TeamOutlined,
// //   UserOutlined,
// // } from '@ant-design/icons';
// import type { MenuProps } from 'antd';
// import { Breadcrumb, Layout, Menu, theme } from 'antd';
// import { RouterItem } from '../../utils/type';
// import { NavLink, Outlet, useNavigate } from 'react-router-dom';
// import { Routerhome } from '../../pages/index';

// const { Header, Content, Footer, Sider } = Layout;

// type MenuItem = Required<MenuProps>['items'][number];



// function getItem(
//   label: React.ReactNode,
//   key: React.Key,
//   icon?: React.ReactNode,
//   children?: MenuItem[],
// ): MenuItem {
//   return {
//     key,
//     icon,
//     children,
//     label,
//   } as MenuItem;
// }

// // const items: MenuItem[] = [
// //   getItem('Option 1', '1', <PieChartOutlined />),
// //   getItem('Option 2', '2', <DesktopOutlined />),
// //   getItem('User', 'sub1', <UserOutlined />, [
// //     getItem('Tom', '3'),
// //     getItem('Bill', '4'),
// //     getItem('Alex', '5'),
// //   ]),
// //   getItem('Team', 'sub2', <TeamOutlined />, [getItem('Team 1', '6'), getItem('Team 2', '8')]),
// //   getItem('Files', '9', <FileOutlined />),
// // ];
// const getstar=(routes:RouterItem[],role:string)=>{
//     const newArr=routes.filter((item)=>{
//         if(!item.role){
//             return true
//         }else{
//             return item.role.includes(role)
//         }
//     })
//     return newArr
// }
// const homeRoutes=(arr:RouterItem[])=>{
//     const items:MenuItem[]=[]
//     arr.forEach((item)=>{
//         if(item.children){
//             items.push(getItem(<NavLink to={item.path}>{item.title}</NavLink>,item.path,item.icon,homeRoutes(item.children)))
//         }else{
//             items.push(getItem(<NavLink to={item.path}>{item.title}</NavLink>,item.path,item.icon))
//         }
//     })
//     return items
// }
// const items=homeRoutes(getstar(Routerhome,'1'))
// const App: React.FC = () => {
//   const [collapsed, setCollapsed] = useState(false);
//   const navigate=useNavigate()
//   const exit=()=>{
//     localStorage.removeItem('token')
//     navigate('/login')
//   }
//   const {
//     token: { colorBgContainer, borderRadiusLG },
//   } = theme.useToken();

//   return (
//     <Layout style={{ minHeight: '100vh' }}>
//       <Sider collapsible collapsed={collapsed} onCollapse={(value) => setCollapsed(value)}>
//         <div className="demo-logo-vertical" />
//         <Menu theme="dark" defaultSelectedKeys={['1']} mode="inline" items={items} />
//       </Sider>
//       <Layout>
//         <Header style={{ padding: 0, background: colorBgContainer }}>
//         欢迎...
//           {
//             localStorage.getItem('token')?<span>
//              用户名:{localStorage.getItem('user')}
//             </span>:""
//           }
//           <button onClick={exit}>退出</button>
//           </Header>

//         <Content style={{ margin: '0 16px' }}>
//           <Breadcrumb style={{ margin: '16px 0' }}>
//             <Breadcrumb.Item>User</Breadcrumb.Item>
//             <Breadcrumb.Item>Bill</Breadcrumb.Item>
//           </Breadcrumb>
//           <div
//             style={{
//               padding: 24,
//               minHeight: 360,
//               background: colorBgContainer,
//               borderRadius: borderRadiusLG,
//             }}
//           >
//            <Outlet></Outlet>
//           </div>
//         </Content>
//         <Footer style={{ textAlign: 'center' }}>
//           Ant Design ©{new Date().getFullYear()} Created by Ant UED
//         </Footer>
//       </Layout>
//     </Layout>
//   );
// };

// export default App;
import React, { useState, useEffect } from 'react';
import { Breadcrumb, Layout, Menu, theme } from 'antd';
import { RouterItem } from '../../utils/type';
import { NavLink, Outlet, useNavigate } from 'react-router-dom';
import { Routerhome } from '../../pages/index';

const { Header, Content,  Sider } = Layout;

type MenuItem = Required<MenuProps>['items'][number];

function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[],
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
  } as MenuItem;
}

// 根据角色过滤路由
const getFilteredRoutes = (routes: RouterItem[], role: string): RouterItem[] => {
  return routes
    .filter(item => !item.role || item.role.includes(role))
    .map(item => ({
      ...item,
      children: item.children ? getFilteredRoutes(item.children, role) : undefined,
    }))
    .filter(item => !item.children || item.children.length > 0); // 移除空子菜单的父项
};

// 将路由转换为菜单项
const generateMenuItems = (routes: RouterItem[]): MenuItem[] => {
  return routes.map(item => ({
    key: item.path,
    icon: item.icon,
    label: <NavLink to={item.path}>{item.title}</NavLink>,
    children: item.children ? generateMenuItems(item.children) : undefined,
  }));
};

const App: React.FC = () => {
  const [collapsed, setCollapsed] = useState(false);
  const [items, setItems] = useState<MenuItem[]>([]);
  const navigate = useNavigate();

  // 从 localStorage 获取当前用户角色（示例，实际可能来自全局状态）
  const currentRole = localStorage.getItem('userRole') || '2'; // 默认角色 '1'

  // 当角色变化时重新计算菜单项
  useEffect(() => {
    const filteredRoutes = getFilteredRoutes(Routerhome, currentRole);
    const menuItems = generateMenuItems(filteredRoutes);
    setItems(menuItems);
  }, [currentRole]); // 依赖 currentRole

  const exit = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('userRole'); // 清除角色
    navigate('/login');
  };

  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();

  return (
    <Layout style={{ minHeight: '100vh' }}>
      <Sider collapsible collapsed={collapsed} onCollapse={setCollapsed}>
        <div className="demo-logo-vertical" />
        <Menu
          theme="dark"
          mode="inline"
          items={items}
          defaultSelectedKeys={[window.location.pathname]}
        />
      </Sider>
      <Layout>
        <Header style={{ padding: 0, background: colorBgContainer }}>
          欢迎...
          {localStorage.getItem('token') && (
            <span>
              用户名: {localStorage.getItem('user')} | 角色: {currentRole}
            </span>
          )}
          <button onClick={exit}>退出</button>
        </Header>
        <Content style={{ margin: '0 16px' }}>
          <Breadcrumb style={{ margin: '16px 0' }}>
            <Breadcrumb.Item>User</Breadcrumb.Item>
            <Breadcrumb.Item>Bill</Breadcrumb.Item>
          </Breadcrumb>
          <div
            style={{
              padding: 24,
              minHeight: 360,
              background: colorBgContainer,
              borderRadius: borderRadiusLG,
            }}
          >
            <Outlet />
          </div>
        </Content>
     
      </Layout>
    </Layout>
  );
};

export default App;